package com.chj.consumer_balance.getmessage;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消费者——拉取模式
 */
public class GetMessageConsumer {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        // 创建信道
        Channel channel = connection.createChannel();
        // 创建交换器 BuiltinExchangeType.DIRECT == direct
//        channel.exchangeDeclare(EXCHANGE_NAME,"direct");
        channel.exchangeDeclare(GetMessageProducer.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        // 声明一个队列
        String queueName = "focuserror";
        channel.queueDeclare(queueName,false,false,false,null);
        //只关注error级别的日志，然后记录到文件中去。
        String routekey="error";
        channel.queueBind(queueName,GetMessageProducer.EXCHANGE_NAME,routekey);
        System.out.println(" [*] Waiting for messages......");
        while(true){
            GetResponse getResponse = channel.basicGet(queueName,false);
            if(null!=getResponse){
                System.out.println("received[" +getResponse.getEnvelope().getRoutingKey()+"]"+new String(getResponse.getBody()));
            }
            channel.basicAck(0,true);
            Thread.sleep(1000);
        }
    }
}
